package com.gexiaobao.pigeon.ui.organizer.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentOrganizerBinding
import com.gexiaobao.pigeon.ui.activity.LoginActivity
import com.gexiaobao.pigeon.ui.adapter.MyPagerAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MemberInfoViewModel
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 11:50
 * @Describe    : 组织方-设备列表
 */
class FragmentOrganizer : BaseFragment<MemberInfoViewModel, FragmentOrganizerBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        val title = KvUtils.decodeString(Constant.ORGANIZATION_NAME)
        mDatabind.toolbar.init(title)
    }

    override fun initData() {
        super.initData()
        initViewPager()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvLogout) {
            when (it) {
                mDatabind.tvLogout -> {
                    showDialog()
                }
            }
        }
    }

    private fun showDialog() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("确定退出吗？")
        dialog.setSureListener {
            dialog.dismiss()
            showLoading("退出中...")
            mViewModel.loginOut()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.logOutResult.observe(this) {
            dismissLoading()
            if (it.isSuccess) {
                CacheUtil.setIsLogin(false)
                KtxActivityManger.finishAllActivity()
                RxToast.showToast("已退出登录")
                startActivity<LoginActivity>()
                //带点渐变动画
                activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun initViewPager() {
        val tabTitles = arrayListOf("会员", "设备")
        val fragments = ArrayList<Fragment>()
        fragments.add(FragmentMemberInfo.newInstance())
        fragments.add(FragmentDeviceList.newInstance(0))
        mDatabind.viewPager.adapter = activity?.let { MyPagerAdapter(childFragmentManager, it, fragments, tabTitles) }
        mDatabind.viewPager.offscreenPageLimit = 2
        mDatabind.tabLayout.setupWithViewPager(mDatabind.viewPager)
    }
}